package TCP和UDP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    Socket socket = null;
    public TcpEchoClient(String serverIp, int serverPort) throws IOException {
        //需要在创建socket的时候与服务器建立连接，服务器的位置在哪得告诉socket
        //具体怎样建立连接的，不是我们所要思考的问题，是操作系统内核自动实现的
        //在socket对象完成创建之时，操作系统就自动完成了三次握手的过程，然后连接就建立完成
        socket = new Socket(serverIp,serverPort);
    }

    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);
            Scanner nextScanner = new Scanner(inputStream)){
            while(true) {
                //1.从控制台读取
                System.out.print("->");
                String request = scanner.next();
                //2.将请求发送到服务器
                printWriter.println(request);
                //刷新内存
                printWriter.flush();
                //3.接收响应并解析
                String response = nextScanner.next();
                System.out.println(response);
            }

        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }

}
